{block name=body}
{function name=class_list level=0} 
  {foreach $fields.options.classes as $opt}
  {if $count eq ""}
  	{assign var=count value=1}
  {else}
  	{assign var=count value=$count+1}
  {/if} 
  <div class="row form-group opt-classes {$opt.extra.location_state}">
     <input type="hidden" value="classterm_id" name="field[3][tbl_classterm][{$count}][id]" />
     <input type="hidden" value="{call name=classterm_id id=$opt.id}" name="field[3][tbl_classterm][{$count}][classterm_id]" class="key" />
     <input type="hidden" value="{$opt.id}" name="field[3][tbl_classterm][{$count}][classterm_class_id]" id="classterm_class_id_{$opt.id}">
     <input type="hidden" value="{$fields.term_id}" name="field[3][tbl_classterm][{$count}][classterm_term_id]" id="classterm_term_id_{$opt.id}" class="key">
     <label class="col-sm-7 control-label" for="classchk_{$opt.id}">{$opt.value} [{$opt.extra.agegroup_shortname}]</label>
     <div class="col-sm-1">
       <input type="hidden" value="{call name=classterm_value id=$opt.id}" name="field[3][tbl_classterm][{$count}][classterm_published]" class="value sync-val" id="classterm_val_{$opt.id}">
       <input class="chckbx sync-chk" type="checkbox" {call name=classterm_selected id=$opt.id} onclick="if($(this).is(':checked')){ $(this).parent().children('.value').val('1') }else{ $(this).parent().children('.value').val('0') }" id="classchk_{$opt.id}"> 
     </div>
   </div>
   {/foreach} 
{/function}
{function name=classterm_value id=""}
	{assign var=val value=0}
	{if $id neq ""}
		{foreach $fields.classterm as $loc}
			{if $id eq $loc.classterm_class_id}
				{assign var=val value=$loc.classterm_published}
				{break}
			{/if}
		{/foreach}
		{$val}
	{/if}
{/function}
{function name=classterm_selected id=""}
	{assign var=val value=0}
		{if $id neq ""}
			{foreach $fields.classterm as $loc}
				{if $id eq $loc.classterm_class_id}
					{assign var=val value=$loc.classterm_published}
					{break}
				{/if}
			{/foreach}
		{/if}
	{if $val eq 1}checked="checked"{/if}
{/function}
{function name=classterm_id id=""}
	{if $id neq ""}
		{foreach $fields.classterm as $loc}
			{if $id eq $loc.classterm_class_id}
				{$loc.classterm_id}
				{break}
			{/if}
		{/foreach}
	{/if}
{/function}


<div class="well row">
	<div class="col-sm-12">
			<div class="row">
				<div class="col-sm-12 edit-page-header">
					<span class="edit-page-title">{if $fields.term_id neq ""}编辑{else}新建{/if} {$zone}</span>
					{if $cnt eq ""}{assign var=cnt value=0}{/if} 
					<a href="javascript:void(0);" onClick="$('#Edit_Record').submit();" class="btn btn-primary pull-right top-btn"><span class="glyphicon glyphicon-floppy-saved"></span> 保存</a>
					<div class="published" {if $fields.term_published eq 0}style="display:none;"{/if}>
						<!-- 已发布 -->
						<!-- <a href="javascript:void(0);" onClick="saveDraft('field[1][tbl_term][{$cnt}][id]','term_object_id','term_published','field[1][tbl_term][{$cnt}][term_deleted]',false);" class="btn btn-info pull-right top-btn published"><span class="glyphicon glyphicon-floppy-disk"></span> 保存草稿</a>
						<a href="javascript:void(0);" onClick="unpublish('term_published');" class="btn btn-warning pull-right top-btn"><span class="glyphicon glyphicon-thumbs-down"></span> 不发布</a> -->
					</div>
					<div class="drafts" {if $fields.term_published eq 1}style="display:none;"{/if}>
						<!-- 草稿 -->
						<a href="javascript:void(0);" onClick="publish('field[1][tbl_term][{$cnt}][id]','term_object_id','term_published','field[1][tbl_term][{$cnt}][term_deleted]');" class="btn btn-primary pull-right top-btn drafts"><span class="glyphicon glyphicon-thumbs-up"></span> 保存 &amp; 发布</a>
					</div>
					
				</div>
			</div>
			<div class="row published" {if $fields.term_published eq 0}style="display:none;"{/if}>
				<div class="alert alert-success text-center">
					<strong>已发布</strong> 
				</div>
			</div>
			<div class="row drafts" {if $fields.term_published eq 1}style="display:none;"{/if}>
				<div class="alert alert-info text-center">
					<strong>草稿</strong>
				</div>
			</div>
			<ul class="nav nav-tabs" id="myTab">
				<li class="active"><a href="#details" data-toggle="tab">详情</a></li>
				<li><a href="#classes" data-toggle="tab">课程</a></li>
				<li><a href="#log" data-toggle="tab">日志</a></li>
			</ul>
		
			<div class="tab-content">
				<!--===+++===+++===+++===+++===+++ DETAILS TAB +++===+++===+++===+++===+++====-->
				<div class="tab-pane active" id="details">
					<div class="row form" data-error="<b>详情</b>选项上发现错误。打开<b>详情</b>选项以查看特定错误通知。">
						<form class="form-horizontal" id="Edit_Record" accept-charset="UTF-8" method="post" data-callback="ProcessClassterms">
						<input type="hidden" value="term_id" name="primary_id" id="primary_id"/> 
						<input type="hidden" value="term_id" name="field[1][tbl_term][{$cnt}][id]" id="id" /> 
						<input type="hidden" value="{$fields.term_id}" name="field[1][tbl_term][{$cnt}][term_id]" id="term_id" class="key"> 
						<input type="hidden" value="{if $fields.term_object_id}{$fields.term_object_id}{else}{$objID}{/if}" name="field[1][tbl_term][{$cnt}][term_object_id]" id="term_object_id"> 
						<input type="hidden" value="{if $fields.term_created}{$fields.term_created}{else}{'Y-m-d H:i:s'|date}{/if}" name="field[1][tbl_term][{$cnt}][term_created]" id="term_created">
						<input type="hidden" value="{$fields.term_published}" name="field[1][tbl_term][{$cnt}][term_published]" id="term_published">
						<input type="hidden" name="formToken" id="formToken" value="{$token}"/>
					
						<div class="row form-group">
							<label class="col-sm-3 control-label" for="id_term_termcategory_id">选择学期 *</label>
							<div class="col-sm-4">
								<select class="form-control required" name="field[1][tbl_term][{$cnt}][term_termcategory_id]" id="id_term_termcategory_id" onchange="updateName()"> 
									<option value="">请选择</option> {foreach $fields.options.termcategories as $opt}
									<option value="{$opt.id}" {if $fields.term_termcategory_id eq $opt.id}selected="selected"{/if}>{$opt.value}</option> {/foreach}
								</select>
							</div>
						</div>
						<div class="row form-group">
							<label class="col-sm-3 control-label" for="id_term_region">地区 *</label>
							<div class="col-sm-3">
								<select class="form-control required" name="field[1][tbl_term][{$cnt}][term_region]" id="id_term_region" onchange="updateName()">
									<option value="">请选择</option>
									{foreach $fields.options.states as $opt}
									<option value="{$opt.value}" data-id="{$opt.id}" {if $fields.term_region eq $opt.value}selected="selected"{/if}>{$opt.value}</option>
									{/foreach}
								</select>
							</div>
						</div>
						<div class="row form-group">
							<label class="col-sm-3 control-label" for="id_term_name">学期名称 *</label>
							<div class="col-sm-5">
								<input class="form-control" type="text" value="{$fields.term_name}" name="field[1][tbl_term][{$cnt}][term_name]" id="id_term_name" onchange="seturl();" required>
								<span class="help-block"></span>
							</div>
						</div>
						<div class="row form-group">
							<label class="col-sm-3 control-label" for="id_class_url">* URL地址</label>
							<div class="col-sm-5">
								<input class="form-control" type="hidden" value="{$fields.term_url}" name="field[1][tbl_term][{$cnt}][term_url]" id="id_term_url" onchange="seturl();" >
                <span id="id_term_url_text" class="form-control url-text edit-url">{$fields.term_url}&nbsp;</span>
                <a href="javascript:void(0);" class="btn btn-info btn-sm marg-5r edit-url" onclick="$('.edit-url').removeClass('url-text').hide();$('#id_term_url').get(0).type='text';">编辑URL地址</a> 
								<span class="help-block"></span>
							</div>
						</div>
						<div class="row form-group">
							<label class="col-sm-3 control-label" for="id_term_content1">描述</label>
							<div class="col-sm-5">
								<textarea name="field[1][tbl_term][{$cnt}][term_content1]" id="id_term_content1" class="tinymce">{$fields.term_content1}</textarea>
							</div>
						</div>
						
						<div class="row form-group">
							<label class="col-sm-3 control-label" for="id_term_start_date">开始日期 *</label>
							<div class="col-sm-5">
								<input class="form-control dates" type="text" value="{if $fields.term_start_date}{$fields.term_start_date}{else}{$smarty.now|date_format:"%Y-%m-%d"}{/if}"  name="from" id="from" onchange="setDateValue('id_term_start_date',this.value);" required>
								<input type="hidden" value="{if $fields.term_start_date}{$fields.term_start_date}{else}{$smarty.now|date_format:"%Y-%m-%d"}{/if}" name="field[1][tbl_term][{$cnt}][term_start_date]" id="id_term_start_date">
							</div>
						</div>
						<div class="row form-group">
							<label class="col-sm-3 control-label" for="id_term_end_date">结束日期 *</label>
							<div class="col-sm-5">
								<input class="form-control dates" type="text" value="{if $fields.term_end_date}{$fields.term_end_date}{/if}"  name="to" id="to" onchange="setDateValue('id_term_end_date',this.value);" required>
								<input type="hidden" value="{if $fields.term_end_date}{$fields.term_end_date}{/if}" name="field[1][tbl_term][{$cnt}][term_end_date]" id="id_term_end_date">
							</div>
						</div>
						<div class="row form-group">
							<label class="col-sm-3 control-label" for="id_term_budget">预算 *</label>
							<div class="col-sm-5">
								<input class="form-control double" type="text" value="{$fields.term_budget}" name="field[1][tbl_term][{$cnt}][term_budget]" id="id_term_budget" required>
								<span class="help-block"></span>
							</div>
						</div>
						</form>
					</div>
				</div>
				<!--===+++===+++===+++===+++===+++ CLASSES TAB +++===+++===+++===+++===+++====-->
        <div class="tab-pane" id="classes">
        	<form class="form-horizontal" id="classterm-form" accept-charset="UTF-8" method="post">
        	<div class="row form form-group">
							<label class="col-sm-3 control-label" for="sync_term"></label>
							<div class="col-sm-5">
		          	<select class="form-control url-text" name="sync_term" id="sync_term">
		          		<option value="" >与上一期课程同步</option>
									{foreach $fields.options.termlist as $opt}
										<option value="{$opt.id}" data-hidden="true" data-region="{$opt.extra.term_region}">{$opt.value}</option>
									{/foreach}
								</select>
								<a id="getclassterm-btn" href="javascript:void(0);" onClick="GetClassTerms('sync_term');" class="btn btn-info btn-sm marg-5r">加载</a>
							</div>
					</div>
					<hr>
          <div class="form">
          	<a href="javascript:void(0);" onClick="changeChkboxes('classterm_wrapper');" class="btn btn-default btn-xs pull-right top-btn ">全选</a>
            <div id="classterm_wrapper"></div>
	        </div>
	        </form>
        </div>
				<!--===+++===+++===+++===+++===+++ LOG TAB +++===+++===+++===+++===+++====-->
				<div class="tab-pane" id="log">
					<div class="row form" id="tags-wrapper">
						<div class="col-sm-12">
							{if $fields.logs}
								<table class="table table-bordered table-striped table-hover">
									<thead>
										<tr>
											<th>时间</td>
											<th>操作</td>
											<th>用户</td>
										</tr>
									</thead>
									<tbody>
									{foreach $fields.logs as $log}
										<tr {if $log.term_id eq $fields.term_id}class="info"{/if}>
											<td>{$log.log_created|date_format:"%d/%b/%Y %r"}</td>
											<td>{$log.log_action}{if $log.log_action eq 'Add' || $log.log_action eq 'Delete'} draft{/if}</td>
											<td>{$log.admin_name}</td>
										</tr>
									{/foreach}
									</tbody>
								</table>
							{else}
								暂无日志。
							{/if}
						</div>
					</div>
				</div>
			</div>
			<div class="row form-group form-bottom-btns">
				<a href="javascript:void(0);" onClick="$('#Edit_Record').submit();" class="btn btn-primary pull-right top-btn"><span class="glyphicon glyphicon-floppy-saved"></span> 保存</a>
				<div class="published" {if $fields.term_published eq 0}style="display:none;"{/if}>
					<!-- 已发布 -->
					<!-- <a href="javascript:void(0);" onClick="saveDraft('field[1][tbl_term][{$cnt}][id]','term_object_id','term_published','field[1][tbl_term][{$cnt}][term_deleted]', false);" class="btn btn-info pull-right top-btn published"><span class="glyphicon glyphicon-floppy-disk"></span> 保存草稿</a>
					<a href="javascript:void(0);" onClick="unpublish('term_published');" class="btn btn-warning pull-right top-btn"><span class="glyphicon glyphicon-thumbs-down"></span> 不发布</a> -->
				</div>
				<div class="drafts" {if $fields.term_published eq 1}style="display:none;"{/if}>
					<!-- 草稿 -->
					<a href="javascript:void(0);" onClick="publish('field[1][tbl_term][{$cnt}][id]','term_object_id','term_published','field[1][tbl_term][{$cnt}][term_deleted]');" class="btn btn-primary pull-right top-btn drafts"><span class="glyphicon glyphicon-thumbs-up"></span> 保存 &amp; 发布</a>
				</div>
			</div>
		
	</div>
</div>

{include file='jquery-validation.tpl'}

<script type="text/javascript">
$(document).ready(function(){
	GetClassTerms();
	
	$('#Edit_Record').validate({
		onkeyup: false
	});
	
	$("#from").datepicker({
		changeMonth : true,
		changeYear : true,
		dateFormat : "yy-mm-dd",
		onSelect : function(selectedDate) {
			$("#id_term_start_date").val( selectedDate );
			$("#to").datepicker("option", "minDate", selectedDate);
		}
	});

	$("#to").datepicker({
		changeMonth : true,
		changeYear : true,
		dateFormat : "yy-mm-dd",
		onSelect : function(selectedDate) {
			$("#id_term_end_date").val( selectedDate );
			$("#from").datepicker("option", "maxDate", selectedDate);
		}
	});
	
});

function seturl(){
	var thisyear = new Date().getFullYear()
	var str = thisyear + ' ' + $('#id_term_termcategory_id option:selected').val() +' | ' + $('#id_term_region option:selected').data("id");
	$.ajax({
		type: "POST",
	    url: "/admin/includes/processes/urlencode.php",
		cache: false,
		data: "value="+encodeURIComponent(str),
		dataType: "json",
	    success: function(res, textStatus) {
	    	try{
	    		if($('#term_id').val() == "" || editexisting == true){
	    		$('#id_term_url').val(res.url);
	    		$('#id_term_url_text').html(res.url);
	    		}
	    	}catch(err){ }
	    }
	});
}

function updateName(){
	var thisyear = new Date().getFullYear()
	var newname = thisyear + ' ' + $('#id_term_termcategory_id option:selected').text() +' | ' + $('#id_term_region option:selected').text();
	$('#id_term_name').val(newname);
	seturl();
}

function saveDraft(id_name,objId_name,publish_name, field_name, preview){
	if ($('#Edit_Record').valid()) { 
		$('body').css('cursor', 'wait');
		$('#'+publish_name).val('0');
		var id_key0 = encodeURIComponent(id_name+'[0]');
		var id_key1 = encodeURIComponent(id_name+'[1]');
		var objId_key = encodeURIComponent($('#'+objId_name).attr('name'));
		var publish_key = encodeURIComponent($('#'+publish_name).attr('name'));
		var field_key = encodeURIComponent(field_name);
		var field_value = encodeURIComponent(mysql_now());
		$.ajax({
			type : "POST",
			url : "/admin/includes/processes/processes-record.php",
			cache: false,
			async: false,
			data : id_key0+'='+objId_name+'&'+id_key1+'='+publish_name+'&'+objId_key+"="+$('#'+objId_name).val()+"&"+publish_key+"=0&"+field_key+"="+field_value+'&formToken='+$('#formToken').val(),
			dataType: "html",
			success : function(data, textStatus) {
				try {
					var obj = $.parseJSON(data);
					if(obj.notice){ 
						$('.key').val('');
						$('#Edit_Record').submit();
						$('.published').hide();
						$('.drafts').show();
// 						buildUrl('tbl_term','term_parent_id',objId_name, preview);
					}
				} catch (err) {}
				$('body').css('cursor', 'default');
			}
		});
		$('body').css('cursor', 'default');
	} 
}

function publish(id_name,objId_name,publish_name,field_name){
	if ($('#Edit_Record').valid()) { 
		$('body').css('cursor', 'wait');
		$('#'+publish_name).val('1');
		var id_key0 = encodeURIComponent(id_name+'[0]');
		var id_key1 = encodeURIComponent(id_name+'[1]');
		var objId_key = encodeURIComponent($('#'+objId_name).attr('name'));
		var publish_key = encodeURIComponent($('#'+publish_name).attr('name'));
		var field_key = encodeURIComponent(field_name);
		var field_value = encodeURIComponent(mysql_now());
		$.ajax({
			type : "POST",
			url : "/admin/includes/processes/processes-record.php",
			cache: false,
			data : id_key0+'='+objId_name+'&'+id_key1+'='+publish_name+'&'+objId_key+"="+$('#'+objId_name).val()+"&"+publish_key+"=1&"+field_key+"="+field_value+'&formToken='+$('#formToken').val(),
			dataType: "html",
			success : function(data, textStatus) {
				try {
					var obj = $.parseJSON(data);
					if(obj.notice){ 
						$('#Edit_Record').submit();
						$('.drafts').hide();
						$('.published').show();
					}
				} catch (err) {}
				$('body').css('cursor', 'default');
			}
		});
		$('body').css('cursor', 'default');
	} 
}

function unpublish(publish_name){
	$('#'+publish_name).val('0');
	$('#Edit_Record').submit();
	$('.published').hide();
	$('.drafts').show();
}


function changeChkboxes(ID){
	var chked = $('#'+ID).find('input:checked');
	if(chked.length > 0){
		$('#'+ID).find('input:checkbox').attr( "checked", false );
		$('#'+ID).find('.value').val('0');
	}else{
		$('#'+ID).find('input:checkbox').attr( "checked", true );
		$('#'+ID).find('.value').val('1');
	}
	
}


$('#id_term_region').change(function() {
	GetClassTerms();
})


function GetClassTerms(TERMFIELD){
	$('#getclassterm-btn').html('加载中...');	
	$('body').css('cursor', 'wait');
	var STATE = $("#id_term_region").val();
	var SYNC = '';
	var ID = $("#term_id").val();
	if(TERMFIELD) {
		ID = $("#"+TERMFIELD).val();
		var SYNC = 'true'; 
	}
	$.ajax({
		type : "POST",
		url : "/admin/includes/processes/processes-classterms.php",
		cache : false,
		data : 'action=GetClassTerm&term_id='+ID+'&term_region='+STATE+'&sync='+SYNC,
		dataType : "html",
		success : function(data, textStatus) {
			try {
				var obj = $.parseJSON(data);
				$('#classterm_wrapper').html('');
				if(obj.template) $('#classterm_wrapper').html(obj.template);	
				if(obj.termlist) {
					$('#sync_term').empty();
					$('#sync_term').append($("<option></option>").attr("value", '').text('与上一期课程同步'));
					$.each(obj.termlist, function(key,value) {
							$('#sync_term').append($("<option></option>").attr("value", value['id']).text(value['value']));
					});	
				}		
				$('#getclassterm-btn').html('加载');
			} catch (err) {}
			$('body').css('cursor', 'default');
		},
		error: function(){
			$('body').css('cursor','default'); 
			console.log('AJAX error');
	  }
	});
}

function ProcessClassterms(){
	$('body').css('cursor', 'wait');
	var ID = $("#term_id").val();
	var datastring = $('#classterm-form').serialize();
	$.ajax({
		type : "POST",
		url : "/admin/includes/processes/processes-classterms.php",
		cache : false,
		data : datastring+'&action=ProcessClassterms&term_id='+ID,
		dataType : "html",
		success : function(data, textStatus) {
			try {
				var obj = $.parseJSON(data);
				var notice = obj.notice;
			 	$('.notification').hide();
			 	$('#'+ notice).slideDown();
				setTimeout(function(){
					$('#'+ notice).slideUp();
		    	},10000);
			} catch (err) {}
			$('body').css('cursor', 'default');
		},
		error: function(){
			$('body').css('cursor','default'); 
			console.log('AJAX error');
	    }
	});
}

</script>
{/block}
